import { createStore } from 'vuex'
//存缓存
const setLocalCartList = (state) =>{
  const { cartList } = state
  const cartListString = JSON.stringify(cartList)
  localStorage.cartList = cartListString
}
//取缓存
const getLocalCartList = () =>{
  /* if(localStorage.cartList){
    return JSON.parse(localStorage.cartList) || {}
  }else{
    return []
  } */
 try{
  return JSON.parse(localStorage.cartList) || {} 
 }catch(e){
  return {}
 }
}

export default createStore({
  state: {
    // cartList:{
    //   shopId:{
    //      shopName:'沃尔玛',
    //         productList:{
    //             111:{
    //               id: 1,
    //               name: "番茄250g/份",
    //               imgUrl:'xxx.png',
    //               sales: 10,
    //               price:33.6,
    //               oldPrice:100,
    //               count:2
    //             },
    //         }
    //   },
    // }
    cartList:getLocalCartList()
  },
  getters: {
  },
  mutations: {
    //加入购物车
    changeCartItemInfo(state,payload){
      const { shopId, productId, productInfo } = payload;
      let shopInfo = state.cartList[shopId] || {};
      let product = shopInfo[productId];
      if(!product){
        productInfo.count = 0
        product = productInfo;
      }
      product.count = product.count + payload.num;
      if(payload.num > 0){
        product.check = true;
      }
      if(product.count <0){
        product.count = 0
      }
      shopInfo[productId]= product;
      state.cartList[shopId] = shopInfo;
      setLocalCartList(state)
    },
    changeShopName(state,payload){
      const { shopId,shopName } = payload
      const shopInfo = state.cartList.shopId || {
        shopName:'', productList:{}
      }
      shopInfo.shopName = shopName
      state.cartList[shopId] = shopInfo
      setLocalCartList(state)
    },
    changeCartItemChecked(state,payload){
      const {shopId ,productId} = payload;
      const product = state.cartList[shopId][productId]
      product.check = !product.check
      setLocalCartList(state)
    },
    cleanCartProducts(state,payload){
      const { shopId } = payload
      state.cartList[shopId] = {}
    },
    setCartItemsChecked(state,payload){
      const { shopId } = payload
      const products = state.cartList[shopId]
      if(products){
         for(let key in products){
          const product = products[key]
          product.check = true;
         }
      }
      setLocalCartList(state)
    },

    clearCartData(state,shopId){
      // state.cartList[shopId].productList = {}
      state.cartList[shopId] = []
    }
  },
})
